package com.example.new1;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import android.util.Log;

public class BookmarkDataHelper{
	
	private static final String DATABASE_NAME = "bookmark.db";
	private static final int DATABASE_VERSION = 2;
	private static final String TABLE_NAME = "bookmark";
	private Context context;
	private SQLiteDatabase db;
	private SQLiteStatement insertStmt;
	private static final String INSERT = "insert into " + TABLE_NAME + " (name) values (?)";
	
	public BookmarkDataHelper(Context context){
		this.context = context;
		OpenHelper openHelper = new OpenHelper(this.context);
		this.db = openHelper.getWritableDatabase();
		this.insertStmt = this.db.compileStatement(INSERT);
	}
	
	public void close(){
		db.close();
	}
	
	public Cursor check(String name){
		Cursor c = db.query(TABLE_NAME, null, "name="+name, null, null, null, null);
		
		if(c != null && c.getCount() != 0)
			c.moveToFirst();
		return c;
	}
	
	public long insert(String name){
		Cursor c = check(name);
		
		if(c != null && c.getCount() != 0){
			this.insertStmt.bindString(1, name);
			return this.insertStmt.executeInsert();
		}
		else
			return 0;
	}
	
	public boolean delete(String name){
		return db.delete(TABLE_NAME, "name="+name, null) > 0;
	}
	
	public void deleteAll(){
		this.db.delete(TABLE_NAME, null, null);
	}
	
	public List<String> selectAll(){
		List<String> list = new ArrayList<String>();
		Cursor cursor = this.db.query(TABLE_NAME, new String[]{"name"}, null, null, null, null, "name desc");
		if(cursor.moveToFirst()){
			do{
				list.add(cursor.getString(0));
			}while(cursor.moveToNext());
		}
		if(cursor != null && !cursor.isClosed()){
			cursor.close();
		}
		return list;
	}
	
	public Cursor getAllColumns(){
		return db.query(TABLE_NAME, null, null, null, null, null, null);
	}
	
	private static class OpenHelper extends SQLiteOpenHelper{

		public OpenHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
			// TODO Auto-generated constructor stub
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			// TODO Auto-generated method stub
			db.execSQL("CREATE TABLE " + TABLE_NAME + " (name TEXT)");
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			// TODO Auto-generated method stub
			Log.w("Example", "Upgrading database, this will drop tables and recreate.");
			db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
			onCreate(db);
		}
		
	}
}
